<?php



namespace app\console\controller;



namespace app\console\controller;



use think\Session;

use think\Url;

use think\Cache;

use think\Loader;

use think\Request;

use think\Controller;

use app\console\model\Ad as AdModel;

use app\console\model\Gift as Model;

use app\common\trilateral\Classify as ClassifyAlias;

use think\Db;

use think\View;



class Gift extends Controller

{





    /**

     * 前置方法

     */

    protected $beforeActionList = [

        'clearCache' => ['only'],

        'default_content' => ['create','update']

    ];





    /**

     * 广告位列表

     */
	public function gift_gangwei_index()
	{
	$param = Request::instance()->param();
	if($param['type']=='index'){
		$gift_id = Request::instance()->param('id');
		$data = Db::name('job')
			->where('status', 1)
			->select()
			->toArray();
		if(!empty($data)){
				foreach ($data as &$v){
					$v['post_xiaoshou'] = Db::name('gift_gangwei')->where(['gift_id' => $gift_id])->where(['post_id' => $v['id']])->value('post_xiaoshou');
					$v['shop_title'] = Db::name('shop')->where(['id' => $v['shop_id']])->value('shop_title');
					if($v['post_xiaoshou']==''){
						$v['post_xiaoshou']='0';
					}
				}
        	 }
		/*$data = Db::name('gift_gangwei g')
		->join('job j', 'g.post_id = j.id')
		->join('shop s', 's.id = j.shop_id')
		->field(['j.title', 'g.*','s.shop_title'])
		->where(['g.gift_id' => $gift_id,])
		->where(['g.is_delete' => '1',])
		->select();*/
        return view('gift_gangwei_ticheng_index', ['data' => $data,'gift_id'=>$gift_id]);
	}elseif($param['type']=='all'){
			$gift_id = Request::instance()->param('gift_id');
			$param1 = Request::instance()->param()['input1'];
			/*************************************************/
			if (!empty($param1)) {

				$ret = false;
	
				foreach ($param1 as $k => $v) {
	
					$find = Db::name('gift_gangwei')->where(['gift_id' => $gift_id])->where(['post_id' => $k])->find();
					if($find){ //存在就是修改
						$ret = Db::name('gift_gangwei')->where(['gift_id' => $gift_id])->where(['post_id' => $k])->update(['post_xiaoshou' => $v]);
					}else{
						$ret = Db::name('gift_gangwei')->insert([
							'gift_id' => $gift_id,
							'post_id' => $k,
							'post_xiaoshou' => $v
						]);
					}
				}
				if ($ret !== false) {
				  wingo('操作成功', Url::build('Gift/gift_gangwei_index',['id' => $gift_id,'type'=>'index']));;
				}
        	}
	}elseif($param['type']=='add'){
			$gift_id = Request::instance()->param('gift_id');
			$data = Db::name('job j')
			->join('shop s', 's.id = j.shop_id')
			->field(['j.*','s.shop_title'])
			->where(['j.status' => '1',])
			->select();
			return view('gift_gangwei_ticheng_add', ['data' => $data,'gift_id'=>$gift_id]);
	}elseif($param['type']=='add_add'){
			$gift_id = Request::instance()->param('gift_id');
			$post_xiaoshou = Request::instance()->param('post_xiaoshou');
			$post_id = Request::instance()->param('post_id');
			$have = Db::name('gift_gangwei')->where(['post_id' => $post_id,])->where(['gift_id' => $gift_id,])->count();
			if($have >'0'){
				wingo('添加失败,该提成已存在', Url::build('Gift/gift_gangwei_index',['id' => $gift_id,'type'=>'index']));
			}else{
				$order_add = Db::name('gift_gangwei')->insert(['gift_id' => $gift_id,'post_id' => $post_id,'post_xiaoshou' => $post_xiaoshou]);
				wingo('操作成功', Url::build('Gift/gift_gangwei_index',['id' => $gift_id,'type'=>'index']));;
			}	
	}elseif($param['type']=='del'){
			$id = Request::instance()->param('id');
			$gift_id = Request::instance()->param('gift_id');
			$finance_pay_cart = Db::name('gift_gangwei')->where(['id' => $id,])->delete();
			wingo('删除成功', Url::build('Gift/gift_gangwei_index',['id' => $gift_id,'type'=>'index']));
			
		}elseif($param['type']=='edit'){
			$gift_id = Request::instance()->param('gift_id');
			$id = Request::instance()->param('id');
			$post_xiaoshou = Db::name('gift_gangwei')->where(['id' => $id,])->value('post_xiaoshou');
			$post_id = Db::name('gift_gangwei')->where(['id' => $id,])->value('post_id');
			$title = Db::name('job')->where(['id' => $post_id,])->value('title');
			return view('gift_gangwei_ticheng_edit', ['gift_id'=>$gift_id,'id'=>$id,'post_xiaoshou'=>$post_xiaoshou,'title'=>$title]);
		}elseif($param['type']=='edit_edit'){
			$gift_id = Request::instance()->param('gift_id');
			$post_xiaoshou = Request::instance()->param('post_xiaoshou');
			$id = Request::instance()->param('id');
			$order_add = Db::name('gift_gangwei')->where('id', $id)->update(['post_xiaoshou' => $post_xiaoshou]);
			wingo('修改成功',Url::build('Gift/gift_gangwei_index',['id' => $gift_id,'type'=>'index']));
		}
	}
    public function index($pa = 10)

    {

        $param = Request::instance()->param();

        $where['card_type'] = ['eq',1];



        if(!empty($param['title'])) $where['title'] = ['like','%'.$param['title'].'%'];

        if (!empty($param['interval_timer'])) {

            $interval_timer = explode(' / ', $param['interval_timer']);

            $where['create_time'] = ['between time', [($interval_timer[0]), ($interval_timer[1])]];

        }



        $data = Model::order(['sort' => 'asc','id' => 'desc'])->where($where)->paginate($pa,false,['query' => $param])->each(function($item,$key){

            $item->mmff =  "(空)";

            $mmff = Db::name('gift_shop_price')->where('gift_id',$item->id)->column('price');

            if(!empty($mmff)){

                foreach ($mmff as $v1){

                    if(!empty($v1) && $v1 != '0.00'){

                        $item->mmff =  "";

                    }

                }

            }
			
			$item->mmaa =  "(空)";

            $mmaa = Db::name('gift_gangwei')->where('gift_id',$item->id)->column('post_xiaoshou');

            if(!empty($mmaa)){

                foreach ($mmaa as $v1){

                    if(!empty($v1) && $v1 != '0.00'){

                        $item->mmaa =  "";

                    }

                }

            }
			
			

        });



        if(isset($param['export'])){

            $this->push_coupon($data);

        }

        return $this->fetch('', [

            'data' => $data,



        ]);

    }



    public function default_content(){

        $default_content = Db::name('single')

            ->order(['sort' => 'asc','id' => 'asc'])

            ->where('parent_id',1)

            ->where('auding_status',2)

            ->where('is_delete',1)

            ->select();

        View::share('default_content',$default_content);

    }



    public function single2($id)

    {

        $default_content = Db::name('single')

            ->order(['sort' => 'asc', 'id' => 'asc'])

            ->where('parent_id', $id)

            ->where('auding_status', 2)

            ->where('is_delete', 1)

            ->field('id,cat_name')

            ->select();

        return ($default_content);

    }



    /**

     * 门店人员提出

     */

    public function shop_ticheng($id)

    {

        if(Request::instance()->isPost()){

            $param = Request::instance()->param()['input2'];

            $goods_id = Request::instance()->param('id');

            if (!empty($param)) {

                $ret = false;

                foreach ($param as $k => $v) {

                    $find = Db::name('gift_shop_price')->where('shop_id', $k)->where('gift_id', $goods_id)->find();

                    if($find){ //存在就是修改

                        $ret = Db::name('gift_shop_price')->where('shop_id', $k)->where('gift_id', $goods_id)->update(['price' => $v]);

                    }else{

                        $ret = Db::name('gift_shop_price')->insert([

                            'gift_id' => $goods_id,

                            'shop_id' => $k,

                            'price' => $v,

                        ]);

                    }



                }

                if ($ret !== false) {

                    win('门店礼包金额设置完毕', Url::build('shop_ticheng',['id' => $goods_id]));

                }

            }

        }

        $goods_id = input('id');

        $shop_list = Db::name('shop')->where('auding_status', 2)->where('is_delete', 1)->select()->toArray();

        if(!empty($shop_list)){

            foreach ($shop_list as &$v){

                $v['price'] = Db::name('gift_shop_price')->where('gift_id',$goods_id)->where('shop_id',$v['id'])->value('price');

            }

        }



        $title = Db::name('gift')->where('id',$id)->value('title');

        return view('', ['shop_list' => $shop_list,'title' => $title]);

    }







    public function push_coupon($data,$name = '礼包导出')

    {



        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)

            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

            ->setCellValue('A1', '科目代码')

            ->setCellValue('B1', '借贷方(绿色借方-灰色贷方)')

            ->setCellValue('C1', 'ID')

            ->setCellValue('D1', '礼包名称')

            ->setCellValue('E1', '礼包价格')

            ->setCellValue('F1', '总次数')

            ->setCellValue('G1', '促销时间')

            ->setCellValue('H1', '销量')

            ->setCellValue('I1', '创建时间')

            ;

        $sheet1 = [];



        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(

                    'font'      => array(

                        'bold' => true

                    ),

                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;

        foreach ($data as $v) {



            $num = $n + 2;

            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

                ->setCellValue('A' . $num, $v['code'])

                ->setCellValue('B' . $num, $v['dc_text'])

                ->setCellValue('C' . $num, $v['id'])

                ->setCellValue('D' . $num, $v['title'])

                ->setCellValue('E' . $num, $v['sale_price'])

                ->setCellValue('F' . $num, $v['count'])

                ->setCellValue('G' . $num, $v['start_time'].'-'.$v['end_time'])

                ->setCellValue('H' . $num, $v['sale_number'])

                ->setCellValue('I' . $num, $v['create_time'])

               ;

            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('礼包导出');

        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');

        exit;

    }



    /**

     * 栏目状态改变

     */

    public function dc($id, Request $request, Model $model)

    {

        $id = $request->instance()->param('id');



        $status = $model->where('id', $id)->value('dc') == '1' ? 2 : 1;



        if ($model->where('id', $id)->update(['dc' => $status])) {

            return $status;

        }

        return false;

    }





    /**

     * 广告位创建

     */

    public function create(Request $request, Model $model)

    {



        if ($request->instance()->isPost()) {



            $data = $request->instance()->param();

            if (!empty($data['single_content']) && count($data['single_content']) != count(array_unique($data['single_content']))) {

                fail('不能添加重复分类');

            }

//            // 验证

//            $validate = Loader::validate('AdType');

//            if (!$validate->scene('create')->check($data)) fail($validate->getError());



            // 提交数据

            $dispose = $model->allowField(true)->save($data);



            if ($dispose) {

                win('操作成功', Url::build('index'));

            }



            fail('操作失败');



        }



        $single_list = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id',0)->select();

        $default_content = Db::name('single')->order(['sort' => 'asc','id' => 'asc'])->where('parent_id',1)->select();

        $single_list = getMenuTree($single_list);

        return $this->fetch('create', [

            'single_list' => json_encode($single_list),

//            'default_content' => json_encode($default_content),

            'gift_count' => []

        ]);



    }



    public function code(){

        $param = Request::instance()->param()['code'];



        if(!empty($param)){



            foreach ($param as $k => $v){



                $ret = Db::name('gift')->where('id',$k)->setField('code',$v);

            }

            if($ret !== false){

                win('科目代码设置成功',Url::build('index'));

            }

        }



    }





    /*

     * 排列顺序

     */

    public function sorting()

    {



        $id = Request::instance()->param('orderId2/a');

        $sort = Request::instance()->param('sort/a');



        if($id){

            foreach ($id as $key => $value) {

                Db::name('gift')->where('id', $value)->update(['sort' => $sort[$key]]);

            }

        }



        winfo('操作成功', Url::build('index', ['orderId' => 'sort']));

    }

    public function goods_sale()

    {



        $id = Request::instance()->param('orderId/a');

        $sort = Request::instance()->param('goods_sale/a');



        if($id){

            foreach ($id as $key => $value) {

                Db::name('gift')->where('id', $value)->update(['goods_sale' => $sort[$key]]);

            }

        }



        winfo('操作成功', Url::build('index', ['orderId' => 'sort']));

    }







    /**

     * 广告位编辑

     */

    public function update($id, Request $request, Model $model)

    {



        if ($request->instance()->isPost()) {



            $data = $request->instance()->param();



            if (!empty($data['single_content']) && count($data['single_content']) != count(array_unique($data['single_content']))) {

                fail('不能添加重复分类');

            }

            // 验证

           // $validate = Loader::validate('AdType');

           // if (!$validate->scene('create')->check($data)) fail($validate->getError());



            // 提交数据

            $dispose = $model->allowField(true)->save($data, ['id' => $id]);





            if ($dispose !== false) {

                wingo('操作成功', Url::build('index'));

            }



            fail('操作失败');



        }

        $single_list = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id',0)->select();

        $single_list2 = \app\console\model\Single::order(['sort' => 'asc','id' => 'asc'])->where(['auding_status' =>2,'is_delete'=>1])->where('parent_id','neq',0)->select();

        $single_list = getMenuTree($single_list);

        $item = Model::get($id);

        $gift_count = Db::name('gift_count')->where('gift_id',$id)->select()->toArray();



        foreach ($gift_count as &$v){

            $v['two_array'] = Db::name('single')->order('sort asc')->where('parent_id',$v['single_id'])->where(['auding_status' => 2,'is_delete' => 1])->select();

        }



        return $this->fetch('create', [

            'gift_count' => $gift_count,

            'single_list' => json_encode($single_list),

            'single_list2' => json_encode($single_list2),

            'item' => $item

        ]);

    }



    public function erjilei($id)

    {

        $single_list2 = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where(['auding_status' => 2, 'is_delete' => 1])->where('parent_id', 'eq', $id)->select();

        return $single_list2;

    }



    /**

     * @param $id

     * @return bool

     * 礼包数量删除

     */

    public function gift_count($id)

    {

        $ret = Db::name('gift_count')->where('id',$id)->delete();

        if($ret){

            return true;

        }

        return false;

    }







    /**

     * 广告位删除

     */

    public function destroy($id, Model $model)

    {



        if (Request::instance()->isGet()) {

            auding_status($id,'title');

            win('操作成功', Url::build('index'));

        }

        fail('操作失败');



    }

    /**

     * 栏目状态改变

     */

    public function status($id, Request $request, Model $model)

    {

        $id = $request->instance()->param('id');



        $status = $model->where('id', $id)->value('status') == '1' ? 2 : 1;



        if ($model->where('id', $id)->update(['status' => $status])) {

            return $status;

        }

        return false;

    }





    /**

     * 栏目全部删除

     */

    public function destroyAll($id, AdTypeModel $adType)

    {



        if ($adType->amputateAll($id)) {



            win('操作成功', Url::build('AdType/index'));

        }



        fail('操作失败');



    }















    /**

     * 清除缓存

     */

    protected function clearCache()

    {

        Cache::rm('AdType');

    }

}